package org.example.aitest.controller;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.example.aitest.domain.User;
import org.example.aitest.dto.wst.WstDTO;
import org.example.aitest.entity.*;
import org.example.aitest.service.*;
import org.example.aitest.utils.gen.ExcelUtil;
import org.example.aitest.utils.HttpClientUploader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    public PurchaseService purchaseService;
    @Autowired
    public CostOrderService costOrderService;
    @Autowired
    public CostInApplyService costInApplyService;
    @Autowired
    public CostInDetailService costInDetailService;
    @Autowired
    public CostInMessageService costInMessageService;
    @Autowired
    public CostMonthApplySingleService costMonthApplySingleService;
    @Autowired
    public CostMonthApplyContractService costMonthApplyContractService;
    @Autowired
    public SupDataService supDataService;
    @Autowired
    public BuopDataService buopDataService;
    @Autowired
    public ConfReceiptService confReceiptService;
    @Autowired
    public IncomeConfirmService incomeConfirmService;
    @Autowired
    public IncomeContractService incomeContractService;
    @Autowired
    public IncomeBidService incomeBidService;
    @Autowired
    public IncomeProjectMessageService incomeProjectMessageService;
    @Autowired
    public IncomeProjectScheService incomeProjectScheService;
    @Autowired
    public IncomeSalesApplyService incomeSalesApplyService;
    @Autowired
    public IncomeSalesXsdetailService incomeSalesXsdetailService;
    @Autowired
    public IncomeSalesKpmessageService incomeSalesKpmessageService;
    @Autowired
    public IncomeSalesKpdetailService incomeSalesKpdetailService;
    @Autowired
    public BidDataService bidDataService;
    @Autowired
    public WbModelService wbModelService;
    @Autowired
    public ProjectBasService projectBasService;
    @Autowired
    public EmployeeSupService employeeSupService;

    @Autowired
    public ExcelUtil excelUtil;

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file, @Validated User user) throws IOException {
        System.out.println("用户信息"+user);
        String name = file.getName();
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        File file1 = new File("D:\\home\\"+originalFilename);
        file.transferTo(file1);
        System.out.println("111"+name);
        System.out.println("222"+originalFilename);
        System.out.println("333"+contentType);
        String uploadUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/files";

//        file.transferTo(Paths.get("D://home//"+file.getOriginalFilename()));
        // 准备文件
        Map<String, File> files = new HashMap<>();
//        files.put("file", new File("C:\\Users\\Admin\\Desktop\\公司基本信息.txt"));

        // 准备其他参数
        Map<String, String> params = new HashMap<>();
        params.put("purpose", "file-extract");
//        params.put("description", "测试文件上传");

        try {
            String response = HttpClientUploader.upload(uploadUrl, files, params);
            System.out.println("上传结果: " + response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @PostMapping("/uploads")
    public List<Long> uploads(@RequestParam MultipartFile[] files) throws IOException {
        List<Long> list = new ArrayList<>();
        for (MultipartFile file : files) {
            long size = file.getSize();
            list.add(size);
        }
        return list;
    }

    /**
     * 文生图
     * */
    @PostMapping("/wst")
    public String wst(@RequestBody WstDTO wstDTO) throws IOException {
        String prompt = "火星上的城市，废土风格。";
        HashMap<String,Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model("wanx2.1-t2i-turbo")
                        .prompt(prompt)
                        .n(2)
                        .size("1024*1024")
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        return null;
    }

    /**
     * 自动根据excel创建表并将数据添加
     * */
    @PostMapping("/exGen")
    public void exGen(@RequestParam MultipartFile file){
        excelUtil.createTableToExcel(file);
    }


    /** TODO 此接口要求数据库要先创建好对应表
     * 读取excel文件
     * */
    @PostMapping("/ex")
    public void ex(@RequestParam MultipartFile file){
        String name = file.getOriginalFilename();

        // 文件后缀
        String la = name.substring(name.lastIndexOf(".")+1);
        try {

            if (la.equals("xlsx")) {
                XSSFWorkbook excel = new XSSFWorkbook(file.getInputStream());

                //表名
                System.out.println(name);


                if (name.contains("采购结果")) {
                    List<Purchase> purchaseList = ExcelUtil.xlsx(excel, Purchase.class, 1, 3, 4, 2);
                    purchaseService.saveBatch(purchaseList);
                } else if (name.contains("成本项目-采购合同")) {
                    List<CostOrder> costOrders = ExcelUtil.xlsx(excel, CostOrder.class, 1, 3, 4, 2);
                    costOrderService.saveBatch(costOrders);
                } else if (name.contains("成本项目-发票入账")) {
                    List<CostInApply> applies = ExcelUtil.xlsx(excel, CostInApply.class, 1, 3, 4, 1);
                    costInApplyService.saveBatch(applies);
                    /**
                     * bb:第二个表
                     * dh:读取表第三行来确定set次数
                     * bh:从第四行开始
                     * bl:从第一列开始
                     * */
                    List<CostInDetail> costInDetails = ExcelUtil.xlsx(excel, CostInDetail.class, 2, 3, 4, 1);
                    costInDetailService.saveBatch(costInDetails);

                    List<CostInMessage> costInMessages = ExcelUtil.xlsx(excel, CostInMessage.class, 3, 3, 4, 1);
                    costInMessageService.saveBatch(costInMessages);
                } else if (name.contains("成本项目-月度批次")) {
                    List<CostMonthApplySingle> costMonthApplySingles = ExcelUtil.xlsx(excel, CostMonthApplySingle.class, 1, 3, 4, 1);
                    costMonthApplySingleService.saveBatch(costMonthApplySingles);

                    List<CostMonthApplyContract> costMonthApplyContracts = ExcelUtil.xlsx(excel, CostMonthApplyContract.class, 2, 3, 4, 1);
                    costMonthApplyContractService.saveBatch(costMonthApplyContracts);
                } else if (name.contains("供应商表格数据")) {
                    List<SupData> supDataList = ExcelUtil.xlsx(excel, SupData.class, 1, 1, 2, 2);
                    supDataService.saveBatch(supDataList);
                } else if (name.contains("商机表格数据")) {
                    List<BuopData> buopDataList = ExcelUtil.xlsx(excel, BuopData.class, 1, 1, 2, 2);
                    buopDataService.saveBatch(buopDataList);
                } else if (name.contains("收货确认")) {
                    List<ConfReceipt> confReceipts = ExcelUtil.xlsx(excel, ConfReceipt.class, 1, 3, 4, 1);
                    confReceiptService.saveBatch(confReceipts);
                } else if (name.contains("收入项目-收入确认")) {
                    List<IncomeConfirm> incomeConfirms = ExcelUtil.xlsx(excel, IncomeConfirm.class, 1, 3, 4, 1);
                    incomeConfirmService.saveBatch(incomeConfirms);
                } else if (name.contains("收入项目-合同信息")) {
                    List<IncomeContract> incomeContracts = ExcelUtil.xlsx(excel, IncomeContract.class, 1, 3, 4, 1);
                    incomeContractService.saveBatch(incomeContracts);
                } else if (name.contains("收入项目-投标信息")) {
                    List<IncomeBid> incomeBids = ExcelUtil.xlsx(excel, IncomeBid.class, 1, 3, 4, 1);
                    incomeBidService.saveBatch(incomeBids);
                } else if (name.contains("收入项目-项目基本信息")) {
                    List<IncomeProjectMessage> incomeProjectMessages = ExcelUtil.xlsx(excel, IncomeProjectMessage.class, 1, 3, 4, 2);
                    incomeProjectMessageService.saveBatch(incomeProjectMessages, 20);
                } else if (name.contains("收入项目-项目进度信息")) {
                    List<IncomeProjectSche> incomeProjectSches = ExcelUtil.xlsx(excel, IncomeProjectSche.class, 1, 3, 4, 1);
                    incomeProjectScheService.saveBatch(incomeProjectSches);
                } else if (name.contains("收入项目-销售开票")) {
                    List<IncomeSalesApply> incomeSales = ExcelUtil.xlsx(excel, IncomeSalesApply.class, 1, 3, 4, 1);
                    incomeSalesApplyService.saveBatch(incomeSales);

                    List<IncomeSalesXsdetail> incomeSalesXsdetails = ExcelUtil.xlsx(excel, IncomeSalesXsdetail.class, 2, 3, 4, 1);
                    incomeSalesXsdetailService.saveBatch(incomeSalesXsdetails);

                    List<IncomeSalesKpmessage> incomeSalesKpmessages = ExcelUtil.xlsx(excel, IncomeSalesKpmessage.class, 3, 3, 4, 1);
                    incomeSalesKpmessageService.saveBatch(incomeSalesKpmessages);

                    List<IncomeSalesKpdetail> incomeSalesKpdetails = ExcelUtil.xlsx(excel, IncomeSalesKpdetail.class, 4, 3, 4, 1);
                    incomeSalesKpdetailService.saveBatch(incomeSalesKpdetails);
                } else if (name.contains("投标数据")) {
                    List<BidData> bidDataList = ExcelUtil.xlsx(excel, BidData.class, 1, 1, 2, 2);
                    for (BidData bidData : bidDataList) {
                        System.out.println("保存数据" + bidData);
                        bidDataService.save(bidData);
                    }
//                bidDataService.saveBatch(bidDataList);
                } else if (name.contains("外包人力模板")) {
                    List<WbModel> wbModels = ExcelUtil.xlsx(excel, WbModel.class, 1, 3, 4, 2);
                    wbModelService.saveBatch(wbModels);
                } else if (name.equals("项目基本.xlsx")) {
                    List<ProjectBas> projectBas = ExcelUtil.xlsx(excel, ProjectBas.class, 1, 3, 4, 2);
                    projectBasService.saveBatch(projectBas);
                } else if (name.contains("员工及供应商")) {
                    List<EmployeeSup> employeeSups = ExcelUtil.xlsx(excel, EmployeeSup.class, 1, 3, 4, 1);
                    employeeSupService.saveBatch(employeeSups);
                }
            } else if (la.equals("xls")) {
                HSSFWorkbook excel = new HSSFWorkbook(file.getInputStream());

                if (name.contains("采购结果")) {
                    List<Purchase> purchaseList = ExcelUtil.xls(excel, Purchase.class, 1, 3, 4, 2);
                    purchaseService.saveBatch(purchaseList);
                } else if (name.contains("成本项目-采购合同")) {
                    List<CostOrder> costOrders = ExcelUtil.xls(excel, CostOrder.class, 1, 3, 4, 2);
                    costOrderService.saveBatch(costOrders);
                } else if (name.contains("成本项目-发票入账")) {
                    List<CostInApply> applies = ExcelUtil.xls(excel, CostInApply.class, 1, 3, 4, 1);
                    costInApplyService.saveBatch(applies);
                    /**
                     * bb:第二个表
                     * dh:读取表第三行来确定set次数
                     * bh:从第四行开始
                     * bl:从第一列开始
                     * */
                    List<CostInDetail> costInDetails = ExcelUtil.xls(excel, CostInDetail.class, 2, 3, 4, 1);
                    costInDetailService.saveBatch(costInDetails);

                    List<CostInMessage> costInMessages = ExcelUtil.xls(excel, CostInMessage.class, 3, 3, 4, 1);
                    costInMessageService.saveBatch(costInMessages);
                } else if (name.contains("成本项目-月度批次")) {
                    List<CostMonthApplySingle> costMonthApplySingles = ExcelUtil.xls(excel, CostMonthApplySingle.class, 1, 3, 4, 1);
                    costMonthApplySingleService.saveBatch(costMonthApplySingles);

                    List<CostMonthApplyContract> costMonthApplyContracts = ExcelUtil.xls(excel, CostMonthApplyContract.class, 2, 3, 4, 1);
                    costMonthApplyContractService.saveBatch(costMonthApplyContracts);
                } else if (name.contains("供应商表格数据")) {
                    List<SupData> supDataList = ExcelUtil.xls(excel, SupData.class, 1, 1, 2, 2);
                    supDataService.saveBatch(supDataList);
                } else if (name.contains("商机表格数据")) {
                    List<BuopData> buopDataList = ExcelUtil.xls(excel, BuopData.class, 1, 1, 2, 2);
                    buopDataService.saveBatch(buopDataList);
                } else if (name.contains("收货确认")) {
                    List<ConfReceipt> confReceipts = ExcelUtil.xls(excel, ConfReceipt.class, 1, 3, 4, 1);
                    confReceiptService.saveBatch(confReceipts);
                } else if (name.contains("收入项目-收入确认")) {
                    List<IncomeConfirm> incomeConfirms = ExcelUtil.xls(excel, IncomeConfirm.class, 1, 3, 4, 1);
                    incomeConfirmService.saveBatch(incomeConfirms);
                } else if (name.contains("收入项目-合同信息")) {
                    List<IncomeContract> incomeContracts = ExcelUtil.xls(excel, IncomeContract.class, 1, 3, 4, 1);
                    incomeContractService.saveBatch(incomeContracts);
                } else if (name.contains("收入项目-投标信息")) {
                    List<IncomeBid> incomeBids = ExcelUtil.xls(excel, IncomeBid.class, 1, 3, 4, 1);
                    incomeBidService.saveBatch(incomeBids);
                } else if (name.contains("收入项目-项目基本信息")) {
                    List<IncomeProjectMessage> incomeProjectMessages = ExcelUtil.xls(excel, IncomeProjectMessage.class, 1, 3, 4, 2);
                    incomeProjectMessageService.saveBatch(incomeProjectMessages);
                } else if (name.contains("收入项目-项目进度信息")) {
                    List<IncomeProjectSche> incomeProjectSches = ExcelUtil.xls(excel, IncomeProjectSche.class, 1, 3, 4, 1);
                    incomeProjectScheService.saveBatch(incomeProjectSches);
                } else if (name.contains("收入项目-销售开票")) {
                    List<IncomeSalesApply> incomeSales = ExcelUtil.xls(excel, IncomeSalesApply.class, 1, 3, 4, 1);
                    incomeSalesApplyService.saveBatch(incomeSales);

                    List<IncomeSalesXsdetail> incomeSalesXsdetails = ExcelUtil.xls(excel, IncomeSalesXsdetail.class, 2, 3, 4, 1);
                    incomeSalesXsdetailService.saveBatch(incomeSalesXsdetails);

                    List<IncomeSalesKpmessage> incomeSalesKpmessages = ExcelUtil.xls(excel, IncomeSalesKpmessage.class, 3, 3, 4, 1);
                    incomeSalesKpmessageService.saveBatch(incomeSalesKpmessages);

                    List<IncomeSalesKpdetail> incomeSalesKpdetails = ExcelUtil.xls(excel, IncomeSalesKpdetail.class, 4, 3, 4, 1);
                    incomeSalesKpdetailService.saveBatch(incomeSalesKpdetails);
                } else if (name.contains("投标数据")) {
                    List<BidData> bidDataList = ExcelUtil.xls(excel, BidData.class, 1, 1, 2, 2);
                    bidDataService.saveBatch(bidDataList);
                } else if (name.contains("外包人力模板")) {
                    List<WbModel> wbModels = ExcelUtil.xls(excel, WbModel.class, 1, 3, 4, 2);
                    wbModelService.saveBatch(wbModels);
                } else if (name.equals("项目基本.xls")) {
                    List<ProjectBas> projectBas = ExcelUtil.xls(excel, ProjectBas.class, 1, 3, 4, 2);
                    projectBasService.saveBatch(projectBas);
                } else if (name.contains("员工及供应商")) {
                    List<EmployeeSup> employeeSups = ExcelUtil.xls(excel, EmployeeSup.class, 1, 3, 4, 1);
                    employeeSupService.saveBatch(employeeSups);
                }
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
